#include "widget.h"
#include "ui_widget.h"

#include <QApplication>
#include <QDesktopWidget>
#include <QGuiApplication>
#include <QLabel>
#include <QScreen>

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
    , m_timer(NULL)
{
    ui->setupUi(this);

    initUI();
}

Widget::~Widget()
{
    delete ui;
}

void Widget::initUI()
{
    //获取当前电脑尺寸
    QScreen* screen = QGuiApplication::primaryScreen();
    QRect screenGemotry = screen->geometry();

    m_screenWidth = screenGemotry.width();
    m_screenHeight = screenGemotry.height();

    //设置窗口宽高
    this->setFixedSize(m_screenWidth, m_screenHeight);

    //设置窗口无边框 和置顶
    setWindowFlags(Qt::FramelessWindowHint | Qt::WindowStaysOnTopHint);

    //设置窗口透明
    setAttribute(Qt::WA_TranslucentBackground, true);

    //当在lineEdit中检测输入回车键就发送
    connect(ui->editInfo, &QLineEdit::returnPressed, this, &Widget::on_btnSend_clicked);

    //设置定时器
    m_timer = new QTimer(this);
    connect(m_timer, &QTimer::timeout, this, &Widget::slot_moveLabel);
    m_timer->start(10);  //周期
}

//发送按钮
void Widget::on_btnSend_clicked()
{
    QString msg = ui->editInfo->text();
    QLabel* lbl = new QLabel(msg, this);
    //设置样式
    QFont font = QFont("微软雅黑", 25);
    lbl->setFont(font);
    QString color = QString("color:rgb(%1,%2,%3).arg(rand()%256).arg(rand()%256).arg(rand()%256)");
    lbl->setStyleSheet(color);

    lbl->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred);

    //获取最佳大小
    QSize preferSize = lbl->sizeHint();
    int x = 0;
    int y = rand()% m_screenHeight;
    lbl->setGeometry(x,y,preferSize.width(), preferSize.height());
    lbl->show();

    //添加到标签列表
    m_lblList.append(lbl);

    //当点击发送按钮后清空label
    ui->editInfo->clear();
}

bool Widget::slot_moveLabel()
{
    QList<QLabel*>::iterator it = m_lblList.begin();
    QPoint moveStep = QPoint(1, 0);
    for(;it != m_lblList.end();)
    {
        QPoint newPos = (*it)->pos() + moveStep;
        (*it)->move(newPos);
        if(newPos.x() > m_screenWidth){
            QLabel *lbl = *it;
            it = m_lblList.erase(it);
            delete lbl;
        } else{
            it++;
        }
    }
    return true;
}

//关闭按钮直接关闭当前widget窗口
void Widget::on_btnStop_clicked()
{
    this->close();
}
